package net.wanho.util;

import cn.hutool.json.JSONUtil;
import net.wanho.vo.AjaxResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Author：汤小洋
 * Date：2023-08-25 16:43
 * Description：ServletUtils工具类
 */
public class ServletUtils {

    /**
     * 获取请求对象
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getRequest();
    }

    /**
     * 获取响应对象
     */
    public static HttpServletResponse getResponse(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getResponse();

    }

    /**
     * 响应Ajax请求，返回json结果
     */
    public static void writeJson(AjaxResult ajaxResult){
        getResponse().setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = getResponse().getWriter();
            writer.write(JSONUtil.toJsonStr(ajaxResult));
        } catch (IOException e) {
            throw new RuntimeException("响应json异常："+e.getMessage());
        } finally {
            if (writer!=null){
                writer.close();
            }
        }
    }
}
